<?php
/**
* @file Comment.php
* @synopsis  用户评论
* @author Yee, <rlk002@gmail.com>
* @version 1.0
* @date 2015-03-11 17:31
*/


class Commentm extends CI_Model
{
    const COMMENTLIST_ASC_KEY = 'comment_list_key_by_asc_';
    const COMMENTLIST_DESC_KEY = 'comment_list_key_by_desc_';
    const COMMENTLIST_PRAISE_KEY = 'comment_list_key_by_praise_';
    const COMMENTLIST_REPLAY_KEY = 'comment_list_replay_key_';
    const COMMENTLIST_ONE_INFO_KEY = 'my_get_one_comment_info_for_key1_';
    
    const QUEUE_COMMENT_NEW = 'queue_comment_new';

    function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取评论详情
     * @param int $comment_id
     */
    public function get_comment_info($comment_id = 0)
    {
        if (!$comment_id) return array();

        $result = $this->db->select('*')
            ->from('ml_comment')
            ->where('id', $comment_id)
            ->get();
        $result = $result->result_array();

        if (!isset($result[0])) return array();
        return $result[0];
    }

    //获取一个帖子的评论内容
    public function get_comment_list($where, $start, $limit)
    {

        //$sql = "select a.*,b.username as author_name,b.id as author_id,b.verified_status as verified_status,b.user_level as user_level,b.admin_level as admin_level,b.head_ico as head_ico,b.thread as thread from ml_comment as a left join ml_fellow as b on a.author_id=b.id where 1 $where order by a.$order_by asc limit $start,$limit";
        //$comment_list = $this->db->query($sql)->result_array();

        $post_id = $where['post_id'];

        $this->db->select("ml_comment.*,ml_fellow.username as author_name,ml_fellow.id as author_id,ml_fellow.verified_status,ml_fellow.user_level,ml_fellow.admin_level,ml_fellow.head_ico,ml_fellow.thread");
        $this->db->join('ml_fellow', 'ml_comment.author_id=ml_fellow.id', "left");
        $this->db->where('ml_comment.post_id', $post_id);
        $this->db->where('ml_comment.is_show', 1);
        $this->db->where('ml_fellow.is_show', 1);
        if ($where['id>']) {
            $this->db->where('ml_comment.id>', $where['id>']);
        }
        $this->db->limit($limit, $start);
        $query = $this->db->from("ml_comment")->get()->result_array();

        if ($query) {
            $comment_list = $query;
        } else {
            return false;
        }

        foreach ($comment_list as $row) {
            //获取评论图片  如果有就显示 没有返回空字符串
            $comment_img_array = $this->db->where(array('cid' => $row['id']))->get('ml_attachments')->result_array();

            $comment_img = $comment_img_array ? $comment_img_array[0]['small'] : '';
            $comment_img_original = $comment_img_array ? $comment_img_array[0]['original'] : '';
            $coment_array = array();
            $coment_array['id'] = $row['id'];
            //$coment_array['author_id'] = $comment_author['author_id'];

            //$coment_array['author_name'] = $comment_author['admin_level']>2 ? "🔅".$comment_author['author_name'] : $comment_author['author_name'];
            $coment_array['verified_status'] = $row['verified_status'];
            //$coment_array['is_admin'] = $comment_author['is_admin'];
            $coment_array['is_expert'] = $row['user_level'] ? 1 : 0;
            $coment_array['admin_level'] = $row['admin_level'];
            $coment_array['author_name'] = $row['author_name'];

            //如果是回复的别人的回复 需要获取被回复人的id和name  否则返回为空
            if ($row['is_replay']) {
                $replay_author = $this->get_replay_author($row['is_replay']);
            } else {
                $replay_author = array('author_id' => '', 'author_name' => '');
            }
            $coment_array['replay_author_id'] = $replay_author['author_id'];
            $coment_array['replay_author_name'] = $replay_author['author_name'];

            $this->load->model("specialtym");
            $coment_array['thread_name'] = $this->specialtym->get_thread_info_by_id($row['thread']);

            $coment_array['thread'] = $row['thread'];
            $coment_array['head_icon'] = ret_fullpath_url($row['head_ico']);

            //获取点赞状态和点赞数
            $this->load->model("commentupm");
            $coment_array['commentup_status'] = $this->commentupm->get_commentup_count(array("comment_id" => $row['id'], "user_id" => $this->uid)) ? 1 : 0;
            $coment_array['commentup_count'] = $this->commentupm->get_commentup_count(array("comment_id" => $row['id']));

            //判断版本

            $row['message'] = $this->preg_deal_user_tips_2($row['message']);
            $coment_array['message'] = $comment_img_original && !$row['message'] ? "如下图所示" : $row['message'];
            $coment_array['relative_post_id'] = $row['relative_post_id'];
            $coment_array['cover_url'] = $row['cover_url'];
            $coment_array['images'] = $comment_img ? ret_fullpath_url($comment_img) : "";
            $coment_array['images_original'] = ret_fullpath_url($comment_img_original);
            $coment_array['addtime'] = $row['addtime'];

            // 2.4新需求评论金额
            $coment_array['money'] = $row['comment_money'];

            $data[] = $coment_array;
        }
        return $data;
    }

    //获取一个帖子的评论内容
    public function get_comment_list_u_v_p($where, $start, $limit, $uid, $vid, $pid)
    {
        $post_id = $where['post_id'];

        $this->db->select("ml_comment.*,ml_fellow.username as author_name,ml_fellow.id as author_id,ml_fellow.verified_status,ml_fellow.user_level,ml_fellow.admin_level,ml_fellow.head_ico,ml_fellow.thread");
        $this->db->join('ml_fellow', 'ml_comment.author_id=ml_fellow.id', "left");
        $this->db->where('ml_comment.post_id', $post_id);
        $this->db->where('ml_comment.is_show', 1);
        $this->db->where('ml_fellow.is_show', 1);
        if ($where['id>']) {
            $this->db->where('ml_comment.id>', $where['id>']);
        }
        $this->db->limit($limit, $start);
        $query = $this->db->from("ml_comment")->get()->result_array();

        if ($query) {
            $comment_list = $query;
        } else {
            return false;
        }

        foreach ($comment_list as $row) {
            $coment_array = array();

            //如果是回复的别人的回复 需要获取被回复人的id和name  否则返回为空
            if ($row['is_replay']) {
                $replay_author = $this->get_replay_author($row['is_replay']);
            } else {
                $replay_author = array('author_id' => '', 'author_name' => '');
            }
            $coment_array['replay_author_id'] = $replay_author['author_id'];
            $coment_array['replay_author_name'] = $replay_author['author_name'];

            //获取评论图片  如果有就显示 没有返回空字符串
            $comment_img_array = $this->db->where(array('cid' => $row['id']))->get('ml_attachments')->result_array();

            $comment_img = $comment_img_array ? $comment_img_array[0]['small'] : '';
            $comment_img_original = $comment_img_array ? $comment_img_array[0]['original'] : '';


            $coment_array['id'] = $row['id'];
            $coment_array['author_id'] = $row['author_id'];

            //$coment_array['author_name'] = $comment_author['admin_level']>2 ? "🔅".$comment_author['author_name'] : $comment_author['author_name'];
            $coment_array['verified_status'] = $row['verified_status'];
            //$coment_array['is_admin'] = $comment_author['is_admin'];
            $coment_array['is_expert'] = $row['user_level'] ? 1 : 0;
            $coment_array['admin_level'] = $row['admin_level'];
            $coment_array['author_name'] = $row['author_name'];


            //获取用户头像和科室
            $this->load->model("specialtym");
            $coment_array['thread_name'] = $this->specialtym->get_thread_info_by_id($row['thread']);
            $coment_array['thread'] = $row['thread'];

            $coment_array['head_icon'] = ret_fullpath_url($row['head_ico']);


            //获取点赞状态和点赞数
            $this->load->model("commentupm");
            $coment_array['commentup_status'] = $this->commentupm->get_commentup_count(array("comment_id" => $row['id'], "user_id" => $this->uid)) ? 1 : 0;
            $coment_array['commentup_count'] = $this->commentupm->get_commentup_count(array("comment_id" => $row['id']));

            /*$coment_array['message'] = $comment_img_original && !$row['message'] ? "如下图所示" : $row['message'];*/

            $coment_array['relative_post_id'] = $row['relative_post_id'];
            $coment_array['cover_url'] = $row['cover_url'];

            //1.引用的是图片如果文字为空，维持现在线上方案 2.引用的是图片如果文字不为空，后边加上 （附图片） 3.引用的是帖子如果文字不为空，后边加上（附帖子） 4.引用的是帖子如果文字为空，加上 如下边引用帖子
            if ($row['relative_post_id']) {
                //如果有帖子 并且有内容 显示 附帖子
                if ($row['cover_url']) {
                    $coment_array['message'] = $row['cover_url'] && !$row['message'] ? "如下帖所示" : $row['message'] . "(附帖子)";
                } else {
                    $coment_array['message'] = $row['message'];
                }


            } else {
                if ($comment_img_original) {
                    //没有帖子  看图片
                    $coment_array['message'] = $comment_img_original && !$row['message'] ? "如下图所示" : $row['message'] . "(附图片)";
                } else {
                    $coment_array['message'] = $row['message'];
                }

            }

            $coment_array['images'] = $comment_img ? ret_fullpath_url($comment_img) : "";
            $coment_array['images_original'] = ret_fullpath_url($comment_img_original);
            $coment_array['addtime'] = $row['addtime'];

            // 2.4新需求评论金额
            $coment_array['money'] = $row['comment_money'];

            $data[] = $coment_array;
        }
        return $data;
    }

    //获取一个帖子的评论列表内容
    public function get_comment_list_1_9_0($post_id, $start, $limit, $order_by, $is_tree)
    {
        $query = $this->fetch_comment_ids($post_id, $order_by);
        $list = array();
        if ($query) {
            if ($is_tree) {
                $classify = $this->classify_comment_ids($query);
                $root_ids = $classify['roots'];
                $child_ids = $classify['children'];

                //取答案
                if ($start == 0) {
                    $answer_comment_info = $this->get_post_answer($post_id);
                    if ($answer_comment_info && $answer_comment_info['is_replay'] == 0) {
                        $answers = $this->tree_for_comment_list(array($answer_comment_info['id']), $child_ids);
                    }
                }

                if ($order_by == 'asc') {
                    sort($root_ids);
                }
                $root_ids = array_slice($root_ids, $start, $limit);

                if ($root_ids) {
                    $list = $this->tree_for_comment_list($root_ids, $child_ids);
                    if ($start == 0 && $answers && $answers[0]) {
                        array_unshift($list, $answers[0]);
                    }
                }
            } else {
                if ($order_by == "asc")//倒序取
                {
                    //如果超出，直接返回空数组
                    if ($start >= count($query)) {
                        return array();
                    }
                    for ($i = count($query) - $start; $i > count($query) - $start - $limit && $i >= 0; $i--) {
                        $row = $query[$i];
                        if ($row) {
                            $comment_info = $this->get_one_comment_info($row['id']);
                            $list[] = $comment_info;
                        }
                    }
                } else {
                    for ($i = $start; ($i < ($start + $limit)) && ($i < count($query)); $i++) {
                        $row = $query[$i];
                        if ($row) {
                            $comment_info = $this->get_one_comment_info($row['id']);
                            $list[] = $comment_info;
                        }
                    }
                }
            }
            return $list;
        } else {
            return false;
        }
    }

    //取评论ID列表
    function fetch_comment_ids($post_id, $order_by)
    {
        $mc = $this->cache->memcached;
        $this->cache->memcached->is_supported();
        if ($order_by == "asc" || $order_by == "desc") {
            $key = self::COMMENTLIST_ASC_KEY . $post_id;
            $query = $mc->get($key);
            if (!$query) {
                $this->db->select("a.id,a.is_replay")->from('ml_comment as a');
                $this->db->join('ml_fellow as b', 'a.author_id=b.id', "left");
                $this->db->where('a.post_id', $post_id);
                $this->db->where('a.is_show', 1);
                $this->db->where('b.is_show', 1);
                $this->db->order_by("a.id", "desc");
                $query = $this->db->get()->result_array();
                $mc->save($key, $query, 60 * 60);
            }
        } else {
            //ml_praise_log
            $key = self::COMMENTLIST_PRAISE_KEY . $post_id;
            $query = $mc->get($key);
            if (!$query) {
                $this->db->select("a.comment_id as id,b.is_replay as is_replay");
                $this->db->join('ml_comment as b', 'a.comment_id=b.id', "left");
                $this->db->join('ml_fellow as c', 'a.author_id=c.id', "left");
                $this->db->where('b.post_id', $post_id);
                $this->db->where('b.is_show', 1);
                $this->db->where('c.is_show', 1);
                $this->db->order_by("a.praise_count", "desc");
                $query = $this->db->from("ml_praise_log as a")->get()->result_array();
                $mc->save($key, $query, 60 * 60);
            }
        }
        return $query;
    }


    /* 获取评论 */



    //评论按照树状排列
    function classify_comment_ids($commentlist_query)
    {
        $root_ids = array();//存最根部的评论ID
        $child_ids = array();

        foreach ($commentlist_query as $one_comment) {
            if ($one_comment['is_replay'] == 0) {
                $root_ids[] = $one_comment['id'];
            } else {
                if (!array_key_exists($one_comment['is_replay'], $child_ids))//
                {

                    $child_ids[$one_comment['is_replay']] = array();
                }
                $child_ids[$one_comment['is_replay']][] = $one_comment['id'];
            }
        }

        return array('roots' => $root_ids, 'children' => $child_ids);
    }

    public function tree_for_comment_list($root_ids, $child_ids)
    {
        $commentlist_infos = array();
        foreach ($root_ids as $rid) {
            $comment_info = $this->get_one_comment_info($rid);
            //字节点ID列表
            $childrens = $this->marge_children_commentlist($rid, $child_ids);

            $sublist = array();
            if ($childrens && count($childrens) > 0) {
                sort($childrens);//子评论顺序变成旧的在前新的在后
                foreach ($childrens as $cid) {
                    $child_comment_info = $this->get_one_comment_info($cid);
                    $sublist[] = $child_comment_info;
                }
            }

            if ($sublist) {
                $comment_info['sub_clist'] = $sublist;
            }
            $commentlist_infos[] = $comment_info;
        }
        return $commentlist_infos;
    }

    function marge_children_commentlist($father, $children_array)
    {
        $child_list = $children_array[$father];
        if ($child_list) {
            foreach ($child_list as $one_father) {
                $next_list = $this->marge_children_commentlist($one_father, $children_array);
                if ($next_list) {
                    $child_list = array_merge($child_list, $next_list);
                }
            }

        }
        return $child_list;
    }

    //取评论ID对应的子评论ID
    public function children_ids_comment_id($post_id, $comment_id)
    {
        $comment_ids = $this->fetch_comment_ids($post_id, 'praise');
        $classify = $this->classify_comment_ids($comment_ids);
        $child_ids = $classify['children'];
        $childrens = $this->marge_children_commentlist($comment_id, $child_ids);

        if (!$childrens) return array();

        return $childrens;
    }

    //过滤标签
    public function preg_deal_user_tips($message)
    {
        $message = preg_replace("/\[user(.*?)\]/", "", $message);
        return $message;
    }

    //过滤标签2
    public function preg_deal_user_tips_2($message)
    {
        $message = preg_replace("/\[user\:(.*?)\:(.*?)\]/", "@$2", $message);
        return $message;
    }

    public function get_replay_author($comment_id)
    {
        $this->db->select("ml_comment.author_id,ml_fellow.username as author_name,ml_fellow.verified_status as verified_status,ml_fellow.admin_level as admin_level,ml_fellow.user_level as user_level,ml_fellow.thread as thread,ml_fellow.head_ico as head_ico");
        $this->db->from("ml_comment");
        $this->db->join("ml_fellow", "ml_comment.author_id=ml_fellow.id", "left");
        $this->db->where(array("ml_comment.id" => $comment_id));
        $result = $this->db->get()->result_array();

        return $return = $result[0];
    }

    /**
     * 获取客户端 评论数
     * @param $post_id
     * @param int $cache
     * @return string
     */
    public function get_count_for_client($post_id, $cache = 1)
    {
        $total = false;
        $key = POST_INFO_PREFIX . $post_id;

        if ($cache == 1) {
            $total = $this->redis->hGet($key, 'comment_total');
        }

        if ($total === false || (int)$total < 0) {
            $where = array('ml_comment.post_id' => $post_id, 'ml_comment.is_show' => 1);
            $this->db->from('ml_comment');
            $this->db->join('ml_fellow', "ml_comment.author_id=ml_fellow.id", "left");
            $this->db->where($where);
            $total = $this->db->count_all_results();
            $this->redis->hSet($key, 'comment_total', $total);
        }

        return (string)$total;
    }

    /**
     * 获取用户自己的回帖数量 （自己看自己）
     * @param int $user_id
     * @param int $type all:获取所有  medical:获取病历
     */
    public function get_user_comment_count($user_id = 0, $type = 'all')
    {
        $filter = array('a.is_show' => 1, 'b.is_show' => 1, 'a.author_id' => $user_id);
        if ($type == 'medical') {
            $this->db->where_not_in('b.post_type_extend', array(4,5));
        }

        $total = $this->db->select('a.post_id')->distinct()->where($filter)->from('ml_comment as a')->join('ml_post as b', 'a.post_id=b.id', 'left')->count_all_results();
        return (string)$total;
    }

    /**
     * 获取目标用户的回帖数量   （自己看别人)）
     * @param int $target_user_id
     * @param string $type
     * @return string
     */
    public function get_target_user_comment_count($target_user_id = 0, $type = 'all')
    {
        $filter = array('a.is_show' => 1, 'b.is_show' => 1, 'a.author_id' => $target_user_id, 'b.post_type <>' => 1);
        if ($type == 'medical') {
            $this->db->where_not_in('b.post_type_extend', array(4,5));
        }

        $total = $this->db->select('a.post_id')->distinct()->where($filter)->from('ml_comment as a')->join('ml_post as b', 'a.post_id=b.id', 'left')->count_all_results();
        return (string)$total;
    }

    /**
     * 获取用户的回帖列表 （当前登录用户自己看自己的）
     * @param int $user_id
     * @param int $add_time
     * @param int $per_page
     * @return array
     */
    public function get_user_comment_post_list($user_id = 0, $add_time = 0, $per_page = 8)
    {
        $key = MY_REPLY_LIST_PREFIX.$user_id;
        $list = unserialize($this->redis->get($key));

        if (empty($list)) {
            $post_ids_result = $this->get_user_comment_post_ids($user_id, $add_time, $per_page);
            $list = array();
            foreach($post_ids_result as $post_id => $addtime) {
                $post_info = $this->postm->get_one_post_info($post_id);
                if ($post_info) {
                    $post_info['comment_addtime'] = $addtime;
                    $list[] = $post_info;
                }
            }

            if ($list) {
                $this->redis->save($key, serialize($list), MY_REPLY_POST_LIST_EXPIRE_TIME);
            }
        }

        return $list;
    }

    /**
     * 获取用户的回帖列表 （当前登录用户看别人的）
     * @param int $user_id
     * @param int $add_time
     * @param int $per_page
     * @return array
     */
    public function get_target_user_comment_post_list($user_id = 0, $add_time = 0, $per_page = 8)
    {
        $key = OTHER_REPLY_POST_LIST_PREFIX.$user_id;
        $list = unserialize($this->redis->get($key));

        if (empty($list)) {
            $post_ids_result = $this->get_target_user_comment_post_ids($user_id, $add_time, $per_page);
            $list = array();
            foreach($post_ids_result as $post_id => $addtime) {
                $post_info = $this->postm->get_one_post_info($post_id);
                if ($post_info) {
                    $post_info['comment_addtime'] = $addtime;
                    $list[] = $post_info;
                }
            }

            if ($list) {
                $this->redis->save($key, serialize($list), MY_REPLY_POST_LIST_EXPIRE_TIME);
            }
        }

        return $list;
    }

    /**
     * 获取用户的回帖ids   当前登录人的（自己看自己）
     * @param int $user_id
     * @param int $page
     * @param int $per_page
     * @return array
     */
    public function get_user_comment_post_ids($user_id = 0, $add_time = 0, $per_page = 24)
    {
        if (!$add_time) $add_time = time();
        $filter = array('a.is_show' => 1, 'b.is_show' => 1, 'a.author_id' => $user_id, 'a.addtime <' => $add_time);

        $result = $this->db->select('a.post_id, a.addtime')
            ->from('ml_comment as a')
            ->join('ml_post as b', 'a.post_id=b.id', 'left')
            ->where($filter)
            ->where_not_in('b.post_type_extend', array(4,5))
            ->order_by('a.id', 'DESC')
            ->group_by('a.post_id')
            ->limit($per_page)
            ->get()
            ->result_array();

        if (!$result) return array();
        return array_column($result,'addtime', 'post_id');
    }

    // 回帖总数（自己看自己）
    public function get_user_comment_post_count($user_id)
    {

        $sql = "select count(1) as count from (
                     SELECT a.id
                    FROM `ml_comment` as `a`
                    LEFT JOIN `ml_post` as `b` ON `a`.`post_id`=`b`.`id`
                    WHERE `a`.`is_show` = 1
                    AND `b`.`is_show` = 1
                    AND `a`.`author_id` =  ".$user_id."
                    AND `a`.`addtime` < ".time()."
                    AND `b`.`post_type_extend` NOT IN(4, 5)
                    GROUP BY `a`.`post_id`  ) as c
                    ";
        $count  = $this->db->query($sql)->row_array();

        return (int)$count['count'];
    }

    /**
     * 获取用户的回帖ids  （当前但登录人查看 其他人的）
     * @param int $user_id
     * @param int $page
     * @param int $per_page
     * @return array
     */
    public function get_target_user_comment_post_ids($target_user_id = 0, $add_time = 0, $per_page = 24)
    {
        if (!$add_time) $add_time = time();
        $filter = array('a.is_show' => 1, 'b.is_show' => 1, 'a.author_id' => $target_user_id, 'a.addtime <' => $add_time, 'b.post_type <>' => 1);

        $result = $this->db->select('a.post_id, a.addtime')
            ->from('ml_comment as a')
            ->join('ml_post as b', 'a.post_id=b.id', 'left')
            ->where($filter)
            ->where_not_in('b.post_type_extend', array(4,5,6))
            ->order_by('a.id', 'DESC')
            ->group_by('a.post_id')
            ->limit($per_page)
            ->get()
            ->result_array();

        if (!$result) return array();
        return array_column($result,'addtime', 'post_id');
    }

    public function get_target_user_comment_post_count($target_user_id)
    {
        $sql = "select count(1) as count from (
                     SELECT a.id
                    FROM `ml_comment` as `a`
                    LEFT JOIN `ml_post` as `b` ON `a`.`post_id`=`b`.`id`
                    WHERE `a`.`is_show` = 1
                    AND `b`.`is_show` = 1
                    AND `a`.`author_id` =  " . $target_user_id . "
                    AND `b`.`post_type_extend` NOT IN(4, 5)
                    AND `b`.`post_type` != 1
                    GROUP BY `a`.`post_id`  ) as c
                    ";
        $count = $this->db->query($sql)->row_array();

        return (int)$count['count'];
    }

	/**
	 * 获取帖字 评论用户数
	 * @param int $post_id
	 */
	public function get_unique_comment_user_count($post_id = 0)
	{
        if (!$post_id) return 0;
		$sql = 'select count(*) as total from (select author_id from ml_comment where post_id='.$post_id.' and  is_show=1 group by author_id) as a';
		$result = $this->db->query($sql);
		$array = $result->result_array();

		if (!isset($array[0]['total'])) return 0;
		return $array[0]['total'];
	}

    public function get_comment_count_expert($post_id)
    {
        $this->db->select();
        $this->db->join("ml_fellow","ml_comment.author_id=ml_fellow.id","left");
        $this->db->where(array("ml_comment.post_id"=>$post_id, "ml_comment.is_show"=>1, "ml_fellow.verified_status"=>3));

        $this->db->from('ml_comment');
        return $this->db->count_all_results();
    }

	//获取用户中心回复帖子 的 id和回复时间
	public function get_commnet_post_time($start,$page_size,$user_id)
	{
		$this->db->select('ml_comment.post_id,ml_comment.addtime');

		$this->db->from('ml_comment');
		$this->db->join('ml_post', 'ml_comment.post_id=ml_post.id','left');

		$this->db->where("ml_comment.is_show",1);
		$this->db->where("ml_comment.author_id",$user_id);

		$this->db->group_by("ml_comment.post_id");
		$this->db->order_by("ml_comment.addtime", "desc");

		$this->db->limit($page_size,$start);

		return $query = $this->db->get()->result_array();


	}

	//插入评论
	public function insert($data)
	{
		$this->db->insert("ml_comment",$data);
        $insert_comment_result =  $this->db->insert_id();
        if($insert_comment_result)
        {
            $this->load->model("commentupm");
            $this->commentupm->insert_comment_praise_init($insert_comment_result, $data['post_id'],$data['author_id']);

        }
        return $insert_comment_result;
    }

	//更新用户回复数(添加)
	public function inc_comment_num_for_fellow($user_id)
	{
		$this->db->set('comment_count', 'comment_count+1', FALSE);
		$this->db->where(array("id"=>(int)$user_id));
		$result = $this->db->update("ml_fellow");
		return $result;
	}

	//更新用户回复数(减少)
	public function dec_comment_num_for_fellow($user_id)
	{
		$this->db->set('comment_count', 'comment_count-1', FALSE);
		$this->db->where(array("id"=>(int)$user_id));
		$result = $this->db->update("ml_fellow");
		return $result;
	}

    /**
     * 更新帖子 回复数 (添加)
     * @param $post_id
     * @return object
     */
	public function inc_comment_num_for_post($post_id, $post_type_extend = 0)
	{
        // 更新rss redis缓存
        $this->load->model('redism');
        if (in_array($post_type_extend, array(0,1,2,3))) {
            $this->redism->zset_incr_comment_total($post_id, 1);
        }

        $key = POST_INFO_PREFIX.$post_id;
        $res = $this->redis->hIncrBy($key, 'comment_total', 1);

        $result = '';
        if ($res) {
            $this->db->set('comment_count', 'comment_count+1', FALSE);
            $this->db->set('lastpost', time());
            $this->db->where(array("id"=>(int)$post_id));
        }
		$result = $this->db->update("ml_post");
		return $result;
	}

    /**
     * 更新帖子 回复数(减少)
     * @param $post_id
     * @return object
     */
	public function dec_comment_num_for_post($post_id, $post_type_extend = 0)
	{
        // 更新rss redis缓存
        $this->load->model('redism');
        if (in_array($post_type_extend, array(0,1,2,3))) {
            $this->redism->zset_incr_comment_total($post_id, -1);
        }

        $key = POST_INFO_PREFIX.$post_id;
        $res = $this->redis->hIncrBy($key, 'comment_total', -1);
        $result = '';
        if ($res) {
            $this->db->set('comment_count', 'comment_count-1', FALSE);
            $this->db->where(array("id"=>(int)$post_id));
            $result = $this->db->update("ml_post");
        }

		return $result;
	}

	//删除帖子时  删除相应的评论
	public function update_comment_status($query,$is_shpw=0)
	{
		$this->db->set(array("is_show"=>$is_shpw));
		$this->db->where($query);
		$result =$this->db->update("ml_comment");
		return $result;
	}

	//获取评论作者id
	public function get_comment_author_id($comment_id)
	{
		$result = $this->db->where(array("id"=>$comment_id))->get("ml_comment")->result_array();
		return $result[0]['author_id'];
	}

	//获取评论信息
	public function get_comment_base_info($comment_id)
	{
		$mc = $this->cache->memcached;
        $key = 'get_comment_info_' . $comment_id;

        if(!$this->cache->memcached->is_supported())
        {
            $result = array("code" => -3,'tips' => "缓存未开启");
        }
        $data = $mc->get($key);
        if($data)
        {
            return $data;
        }
        else {
            $result = $this->db->where(array("id" => $comment_id))->get("ml_comment")->result_array();
            $data = $result[0];
            $mc->save($key,$data, 60*10);
            return $data;
        }
	}


	//获取某个帖子的所有回复的用户的id  去重
	public function get_comment_user($query)
	{
		return $result = $this->db->select("distinct(author_id)")->where($query)->get("ml_comment")->result_array();
	}

	//获取评论内容
	public function get_comment_message($comment_id)
	{
        $mc = $this->cache->memcached;
        $key = 'get_comment_message_' . $comment_id;

        if(!$this->cache->memcached->is_supported())
        {
            $result = array("code" => -3,'tips' => "缓存未开启");
        }
        $data = $mc->get($key);
        if($data)
        {
            return $data;
        }
        else {
            $result = $this->db->where(array("id" => $comment_id))->get("ml_comment")->result_array();
            $data = $result[0]['message'];
            $mc->save($key,$data, 60*10);
            return $data;
        }
	}
    //获取选为答案的评论
    public function get_post_answer($post_id)
    {
        $comment_info = array();
        $filters = array("post_id" => $post_id, "is_answer" => 1, "is_show" => 1);
        $data = $this->db->where($filters)->get("ml_comment")->row_array();
        if ($data) {
            $comment_info = $this->get_one_comment_info($data['id']);
        }
        return $comment_info;
    }

    //获取单条评论数据
    public function get_one_comment_info($comment_id)
    {
        $mc = $this->cache->memcached;
        $key = self::COMMENTLIST_ONE_INFO_KEY . $comment_id;
        $data = $mc->get($key);
        $data = false;
        $coment_array = array();
        if($data)
        {
            $coment_array = $data;
        }
        else
        {
            $filters = array('a.id' => $comment_id, 'a.is_show' => 1, 'b.is_show' => 1);
            $this->db->select("a.*,b.username as author_name,b.id as author_id,b.verified_status,b.user_level,b.admin_level,b.head_ico,b.thread,b.is_show_truename as is_show_truename,b.truename as truename, b.practice_hospital as practice_hospital,b.post_title as post_title");
            $this->db->join('ml_fellow as b', 'a.author_id=b.id', "left");
            $this->db->where($filters);
            $row = $this->db->from("ml_comment as a")->get()->row_array();

            //如果是回复的别人的回复 需要获取被回复人的id和name  否则返回为空
            if($row['is_replay'])
            {
                $replay_author = $this->get_replay_author($row['is_replay']);
            }
            else
            {
                $replay_author = array('author_id'=>'','author_name'=>'');
            }
            $coment_array['replay_author_id'] = $replay_author['author_id'];
            $coment_array['replay_author_name'] = $replay_author['author_name'];
            $coment_array['replay_comment_id'] = $row['is_replay'];

            if (! empty($row['images'])) {
                $comment_img_original = $row['images'];
                $comment_img = get_alipic_url($comment_img_original, 'x');
            }
            else {
                //获取评论图片  如果有就显示 没有返回空字符串
                $filters = array('cid' => $row['id']);
                $comment_img_array = $this->db->where($filters)->get('ml_attachments')->result_array();
                $comment_img = $comment_img_array ? $comment_img_array[0]['small'] : '';
                $comment_img_original = $comment_img_array ? $comment_img_array[0]['original'] : '';
            }

            //获取音频 的地址和时长
            $coment_array['voice_path'] = empty($row['voice_path']) ? '' : VOICE_DOWNLOAD_URL . $row['voice_path'];
            $coment_array['voice_times_long'] = $row['voice_times_long'];
            $coment_array['type_id'] = $row['type_id'];
            $coment_array['id'] = $row['id'];
            $coment_array['author_id'] = $row['author_id'];
            $coment_array['verified_status'] = $row['verified_status'];
            $coment_array['is_expert'] = $row['user_level'] ? 1 : 0;
            $coment_array['admin_level'] = $row['admin_level'];

            //获取用户头像和科室
            $this->load->model("specialtym");
            $coment_array['thread_name'] = $this->specialtym->get_thread_info_by_id($row['thread']);
            $coment_array['thread'] = $row['thread'];
            $coment_array['head_icon'] = ret_fullpath_url($row['head_ico']);
            $coment_array['author_name'] = $row['author_name'];
            // 2.4新需求评论金额
            $this->load->Model("tradem");
            $balance = round($this->tradem->convertFen2Yuan($row['comment_money']), 2);
            $coment_array['money'] = $balance;

            if($row['is_show_truename'] == 1)
            {
                if($row['truename'] && strcmp($row['truename'], $row['author_name']) != 0)
                {
                    $coment_array['author_name'] = $row['truename'].'「'.$row['author_name'].'」';
                }
            }
            //所有认证用户都展示医院
            if($row['verified_status'] == 3)
            {
                $this->load->model("userm");
                $verified_info = $this->userm->verified_info($row['author_id']);
                /*$hospital =  $verified_info['hospital'];
                if(!$hospital)
                {
                    $hospital = $row['practice_hospital'];
                }*/
                $hospital = $row['practice_hospital'];
                $coment_array['practice_hospital'] = $hospital;
                if(version_compare($this->softversion, '1.9.3') <= 0)
                {
                    $coment_array['thread_name'] = $hospital.' '.$coment_array['thread_name'];
                }
                else
                {
                    ci_load_once('posttitlem');
                    $row['post_title'] = $this->posttitlem->getPosttitleName($row['post_title']);
                    $coment_array['thread_name'] = $coment_array['thread_name'].' '.$row['post_title'];
                }
            }

            $coment_array['relative_post_id'] = $row['relative_post_id'];
            $coment_array['cover_url'] = $row['cover_url'];

            if($row['relative_post_id'])
            {
                //如果有帖子 并且有内容 显示 附帖子
                if($row['cover_url'])
                {
                    $coment_array['message'] = $row['cover_url'] && !$row['message'] ? "如下帖所示" : $row['message']."(附帖子)";
                }
                else
                {
                    $coment_array['message'] = $row['message'];
                }
            }
            else
            {
                if($comment_img_original)
                {
                    //没有帖子  看图片
                    $coment_array['message'] = $comment_img_original && !$row['message'] ? "如下图所示" : $row['message']."(附图片)";
                }
                else
                {
                    $coment_array['message'] = $row['message'];
                }
            }
            $coment_array['images'] = $comment_img ? ret_fullpath_url($comment_img) : "";
            $coment_array['images_original'] = ret_fullpath_url($comment_img_original);
            $coment_array['addtime'] = $row['addtime'];
            $coment_array['is_answer'] = $row['is_answer'];

            // v2.4 版主积分打赏权限
            $user_info = $this->userm->getUserInfoById($this->uid);
            $coment_array['moderator_reward'] = $this->user_point_comment_authority($this->uid, 2, $row['id'], $user_info['admin_level'], $row['author_id']);
            $mc->save($key,$coment_array, 60*10);
        }


        //获取点赞状态和点赞数

        $this->load->model("commentupm");
        $coment_array['commentup_status'] = $this->commentupm->get_commentup_count(array("comment_id"=>$coment_array['id'],"user_id"=>$this->uid)) ? 1 : 0;
        $coment_array['commentup_count'] = $this->commentupm->get_commentup_count(array("comment_id"=>$coment_array['id']));

        $this->load->model("commentdownm");
        $coment_array['commentdown_status'] = $this->commentdownm->get_commentdown_count(array("comment_id"=>$coment_array['id'],"user_id"=>$this->uid)) ? 1 : 0;
		$coment_array['commentdown_count']  = $this->commentdownm->get_commentdown_count(array("comment_id"=>$coment_array['id']));
        return $coment_array;
    }


    // v2.4 版主积分打赏评论权限
    public function user_point_comment_authority($uid = 0, $type = 1, $related_id = 0, $admin_level = 0, $author_comment_id)
    {
        $user_level = array(3, 4);
        // 非版主不可打赏
        if (!in_array($admin_level, $user_level)) return 0;
        // 版主不能打赏自己的帖子
        if ($uid == $author_comment_id) return 0;
        // 可以进行打赏操作（验证是否已经打赏过）
        $count = $this->postm->get_acc_point_flag($uid, $type, $related_id);
        if ($count) return 2;
        return 1;
    }

    public function fetch_all_comment_list()
    {
        $this->db->select('id,author_id,post_id');
        $this->db->from('ml_comment');
        return $this->db->get()->result_array();
    }

    //获取评论内容黑名单
    public function get_black_comment_content_list()
    {
        return array(
            "学习","学习了","学习一下","学习啦","赞","顶","同意","谢谢分享","感谢分享","多谢分享","谢谢","同意楼上","顶一下","顶","顶一个","顶上","顶一个先","点赞","赞成","赞一个","赞同","大赞","不错","收藏","收藏一下","已收藏","收藏了","支持典型","典型","非常典型","太典型了","很典型","支持","支持楼上","支持一下","受教了","涨姿势","好","牛","长知识","看看","不错"
        );
    }


    /**
     * 所有参与过帖子评论的人
     */
    public function getPostCommentUserIDs($post_id)
    {
        $this->db->select("author_id");
        $this->db->where(array("post_id" => $post_id, "is_show" => 1));
        $this->db->group_by("author_id");
        $query = $this->db->get('ml_comment');
        
        $comment_user_ids = array();
        if ($query) {
            $data = $query->result_array();
            $comment_user_ids = array_column($data, "author_id");
        }
        
        return $comment_user_ids;
    }


    public function afterCommentRelateWork($comment_id)
    {
        $comment_info = $this->get_comment_base_info($comment_id);
        if (empty($comment_info) || (isset($comment_info["is_show"]) && $comment_info["is_show"] == 0)) {
            return false;
        }
        $this->load->model("postm");
        $this->load->model("userm");
        $this->load->model("messagem");
        $this->load->model('invitem');
        $this->load->model('pushm');

        $post_info = $this->postm->get_post_info($comment_info["post_id"]);
        $comment_author_info = $this->userm->getUserInfo($comment_info["author_id"]);

        $message = $comment_info["message"];
        $message = $this->preg_deal_user_tips($message);
        $post_id = $comment_info["post_id"];
        $author_id = $comment_info["author_id"];
        $comment_img_original = $comment_info["images"];

        $author_name = $comment_author_info["username"];
        $post_author_id = $post_info["author_id"];
        $post_type_extend = $post_info["post_type_extend"];
        $replied_comment_id = $comment_info["is_replay"] ? $comment_info["is_replay"] : 0;
        $invite_sent_from = $this->invitem->invite_send_uid($post_id, $author_id);  // 发过邀请给评论者的用户

        $disallow_arr = array($post_author_id, $author_id);                         // 不被允许发送的人

		$logstr = 'afterCommentRelateWork comment_id:' . $comment_id . '|post_id:' . $post_id . '|post_author_id:' . $post_author_id  . '|comment_author_id:' . $author_id .'|';
		w_log($logstr . '_1');

        if($comment_img_original)
        {
            //如果有评论图片 就放入插件数据库
            //取图片的宽高
            $this->load->model('imagem');
            $img_info = $this->imagem->getimagesize($comment_img_original);
            $width = $img_info[0];
            $height = $img_info[1];

            insert_attch_image($this->db,$author_id,$post_id,$comment_id, $comment_img_original,$isappend = 0,$width,$height);
        }


        # 给被回复的人发消息
        if ($replied_comment_id) {
            $replied_author_id = $this->get_comment_author_id($replied_comment_id);
            if ($replied_author_id && !in_array($replied_author_id, $disallow_arr)) {
                $send_content = "[user:" . $author_id . ":" . $author_name . "] 在评论中回复了你：" . $message;
                $this->messagem->send_message($post_id, $replied_author_id, $send_content, $author_id);

                $disallow_arr[] = $replied_author_id;                               // 更新禁发列表
				w_log($logstr . '_2_send_message');
            }
        }



        // 发起过邀请的人
        $invite_users = $this->invitem->invite_related_uids($post_id);
        // 评论过此帖的人
        $comment_user_ids = $this->getPostCommentUserIDs($post_id);

        // 参与过帖子的人
        $relative_uids = array_merge($invite_users, $comment_user_ids);
        $relative_uids[] = $post_author_id;                                         // 帖子作者也参与了
        $relative_uids = array_unique($relative_uids);

        # 专家问诊帖, 特殊处理, 发 PUSH
        if($post_info['post_type'] == 1)
        {
            if ($post_info['post_type_extend'] != 4 && $post_info['post_type_extend'] != 5) {

                $push_message = $author_name . '在评论中回复了你';
                $extras = array('post_id' => $post_id);
                if ($relative_uids) {
                    $to_uids = $relative_uids;
                    foreach ($to_uids as $k => $v) {
                        if (in_array($v, $disallow_arr)) {
                            unset($to_uids[$k]);
                            continue;
                        }
                    }
                    $to_uids = array_values($to_uids);
                    $this->pushm->sendByUserIDArr($to_uids, $push_message, $extras);
                }
            }
        }


        # 如果是被邀请评论的
        if ($invite_sent_from && $post_author_id != "31495") {
            foreach ($invite_sent_from as $k => $v) {
                if (in_array($v, $disallow_arr)) {
                    unset($invite_sent_from[$k]);
                }
            }

            if ($invite_sent_from) {
                $send_content = "[user:" . $author_id . ":" . $author_name . "] 在你的邀请下回复了帖子：" . $message;
                $inviters = array_values($invite_sent_from);
                $this->messagem->send_message($post_id, $inviters, $send_content, $author_id);

                $disallow_arr = array_merge($disallow_arr, $inviters);                    // 更新禁发列表
				w_log($logstr . '_3_send_message');
            }
        }


        # 参与过帖子的人
        if ($relative_uids && $post_author_id != "31495") {
            foreach ($relative_uids as $k => $v) {
                if (in_array($v, $disallow_arr)) {
                    unset($relative_uids[$k]);
                    continue;
                }
            }
            if ($relative_uids) {
                if (in_array($post_info['post_type_extend'], array(4, 5))) {
                    if ($post_info['post_type_extend'] == 4) {
                        $send_content = "[user:" . $author_id . ":" . $author_name . "] 回复了你参与的问答：" . $message;
                    }
                    if ($post_info['post_type_extend'] == 5) {
                        $send_content = "[user:" . $author_id . ":" . $author_name . "] 回复了你参与的投票：" . $message;
                    }
                } else {
                    $send_content = "[user:" . $author_id . ":" . $author_name . "] 回复了你参与的帖子：" . $message;
                }
                $this->messagem->send_message($post_id, $relative_uids, $send_content, $author_id);
                w_log($logstr . '_4_send_message');
            }
        }


        # 给帖子作者发消息（问答投票放开）
        if ($author_id != $post_author_id) {
            if (in_array($post_info['post_type_extend'], array(4, 5))) {
                if ($post_info['post_type_extend'] == 4) {
                    $send_content = "[user:" . $author_id . ":" . $author_name . "] 评论了你发布的问答：" . $message;
                }
                if ($post_info['post_type_extend'] == 5) {
                    $send_content = "[user:" . $author_id . ":" . $author_name . "] 评论了你发布的投票：" . $message;
                }
            } else {
                $send_content = "[user:" . $author_id . ":" . $author_name . "] 评论了你发布的帖子：" . $message;
            }
            $this->messagem->send_message($post_id, $post_author_id, $send_content, $author_id);
            w_log($logstr . '_4.5_send_post_author');
        }


        # at 列表发 PUSH
        $at_friend_list = $comment_info["at_friend_list_id_array"] ? json_decode($comment_info["at_friend_list_id_array"], 1) : null;
        if ($at_friend_list) {
            //首先要去重
            $at_friend_id_list = array_unique($at_friend_list);
            $message = '您的好友@' . $author_name . ' 在评论中提到了您';
            $extras = array('post_id'=>$post_id);
            if($at_friend_id_list)
            {
                $at_friends = array_values($at_friend_id_list);
                $push_result = $this->pushm->sendByUserIDArr($at_friends, $message, $extras);
				w_log($logstr . '_5_send_push');
            }
        }


        # 评论成功后  如果有人邀请我 那么有效回答 则给分 每天十积分  被删除时 不减分
        $invite_send_uid = $this->invitem->invite_send_uid_not_answer($post_id,$author_id);
        //只要回答就给分 不再判断是否为有效邀请
        //if($invite_send_uid && iconv_strlen($message,"UTF-8") >= 10)
        if($invite_send_uid)
        {
            $this->load->model('newjfpointsm');
            if($post_type_extend == 4)
            {
                $jf_relative_type1 = QUESTION_INVITED_COMMENT;
                $jf_relative_type2 = QUESTION_INVITED_COMMENT_SUCCESS;
            }
            else
            {
                $jf_relative_type1 = INVITED_COMMENT;
                $jf_relative_type2 = INVITED_COMMENT_SUCCESS;
            }
            $this->newjfpointsm->add_minusjf_sendmessage($author_id,$post_id,$jf_relative_type1,$post_id,Newjfpointsm::ADD_TYPE);


            //更新邀请状态 变为已回答 避免重复给分
            $this->invitem->update_invite_status($post_id,$author_id);
            //邀请人也有积分
            foreach($invite_send_uid as $invite_me_id)
            {
                //
                $this->newjfpointsm->add_minusjf_sendmessage($invite_me_id,$post_id,$jf_relative_type2,$post_id,Newjfpointsm::ADD_TYPE);

            }
			w_log($logstr . '_6_comment_jf_add');
        }

        //作者自己不加分
        if($post_author_id != $author_id)
        {
            //给评论加积分
            $this->load->model('postjfm');
            $this->postjfm->comment_jf_add($comment_id,$comment_info,$post_info,$author_id);
			w_log($logstr . '_7_comment_jf_add');
            //问答帖被普通用户评论	帖主+1积分    问答帖被大V和版主评论	帖主+3积分
            //w_log('$post_id is '.$post_id.'   post_type_extend is '.$post_info['post_type_extend']);
            if($post_info['post_type_extend'] == 4)
            {
                if ($comment_author_info['user_level'] > 0 || $comment_author_info['admin_level'] > 0)
                {
                    $jf_relative_type3 = QUESTION_COMMENT_EXPERT;
                }
                else
                {
                    $jf_relative_type3 = QUESTION_COMMENT_NORMAL;
                }

                $this->newjfpointsm->add_minusjf_sendmessage($post_author_id,$post_id,$jf_relative_type3,$post_id,Newjfpointsm::ADD_TYPE);
            }

            
        }


        //写入用户行为日志//123
        if($post_info['post_type'] == 0)
        {
            $this->load->model("usereventlogm");
            $event_log_array = array();
            $event_log_array['action'] = "insert_comment";
            $event_log_array['action_type'] = 2;
            $event_log_array['type'] = 1;
            # 兼容
            if (isset($post_info['post_type_extend']) && $post_info['post_type_extend']) {
                $info = $this->usereventlogm->get_action_repect($post_info['post_type_extend']);
                $event_log_array['action'] = $info['action'];
                $event_log_array['action_type'] = $info['action_type'];
                $event_log_array['type'] = $info['type'];
            }
            $event_log_array['uid1'] = $author_id;
            $event_log_array['uid2'] = $post_author_id;
            $event_log_array['post_id'] = $post_id;
            $event_log_array['comment_id'] = $comment_id;
            $event_log_array['addtime'] = time();
            $this->usereventlogm->insert_user_event_log($event_log_array);
        }

        return true;
    }


    // v2.4获取单个评论的用户ID
    public function get_comment_user_id($comment_id)
    {
        $filters = array('id' => $comment_id, 'is_show' => 1);
        $res = $this->db->select('author_id')->from('ml_comment')->where($filters)->get()->row_array();
        return $res['author_id'];
    }



    public function getBonusMoney($comment_id)
    {
        $filters = array('id' => $comment_id, 'is_show' => 1);
        $query = $this->db->select('comment_money')->from('ml_comment')->where($filters)->get();

        $money = 0;
        if ($query) {
            $data = $query->row_array();
            $money = isset($data['comment_money']) ? $data['comment_money'] : 0;
        }

        return $money;
    }
}
